package com.jeffpalm.pandoralastfm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jeffpalm.pandoralastfm.PandoraLastFmBridge.BridgeResult;

/**
 * A simple command line client using the bridge.
 */
public class Repl extends App {

  public static void main(String[] args) {
    new Repl().realMain(args);
  }

  private void realMain(String[] args) {
    while (menu()) {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        handle(e);
      }
    }
    System.err.println("Done.");
  }

  /**
   * Returns <code>false</code> if we want to quit.
   * 
   * @return <code>false</code> if we want to quit
   */
  private boolean menu() {
    abstract class R implements Runnable {
      private final String name;

      R(String name) {
        this.name = name;
      }

      public String name() {
        return name;
      }
    }
    final R[] rs = { new R("Down track") {
      public void run() {
        report(getBridge().down());
      }
    }, new R("Up track") {
      public void run() {
        report(getBridge().up());
      }
    }, new R("Next track") {
      public void run() {
        report(getBridge().next());
      }
    }, };

    // Print current status
    outln("");
    outln(getStatusString());

    // Print menu
    for (int i = 0; i < rs.length; i++) {
      outln("[" + (i + 1) + "] " + rs[i].name());
    }
    String s = prompt("Please enter a selection");

    // recur?
    if (s == null) return menu();
    s = s.trim();
    if (s.equals("")) return menu();

    // quit?
    s = s.toLowerCase();
    if (s.startsWith("q")) return false;

    // allow some special ones
    if (s.equals("d")) {
      s = "1";
    } else if (s.equals("u")) {
      s = "2";
    } else if (s.equals("n")) {
      s = "3";
    }

    int choice = -1;
    try {
      choice = Integer.parseInt(s);
      if (choice >= 1 && choice <= rs.length) {
        final int n = choice - 1;
        new Thread(new Runnable() {
          public void run() {
            rs[n].run();
          }
        }).start();
        return true;
      }
    } catch (NumberFormatException e) {
      System.err.println("Invalid choie:" + choice);
    }
    return menu();
  }

  private void report(BridgeResult res) {
    String msg = res.getMessage();
    if (msg != null) {
      outln(" *** " + msg + " ***");
      outln("");
    }
  }

  private String prompt(String msg) {
    out(msg);
    out("> ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int n = -1;
    try {
      n = in.read();
    } catch (IOException e) {
      handle(e);
    }
    return String.valueOf((char) n);
  }
}
